/**
*@Author: QWP
*@Description:  数学计算结果精度封装
*@Params:
*@Date 2024-07-18 12:41
*/


/**
*@Author: QWP
*@Description: 数据加法，
*@Date 2024-07-18 12:41
*/
export const addC = (num1: number, num2: number): number => {
  let val1 = 0;
  let val2 = 0;

  if(num1.toString().split('.').length > 1){
    val1 = num1.toString().split('.')[1].length;
  }

  if(num2.toString().split('.').length > 1){
    val2 = num2.toString().split('.')[1].length;
  }

  let p = val1 > val2 ? val1 : val2;

  let r1 = takeC(num1, 10**p);
  let r2 = takeC(num2, 10**p);
  let total = divideC((r1 + r2) , (10**p));
  return total
}


/**
*@Author: QWP
*@Description: 数据减法
*@Date 2024-07-18 12:41
*/
export const reduceC = (num1: number, num2: number) => {
  let val1 = 0;
  let val2 = 0;

  if(num1.toString().split('.').length > 1){
    val1 = num1.toString().split('.')[1].length;
  }

  if(num2.toString().split('.').length > 1){
    val2 = num2.toString().split('.')[1].length;
  }

  let p = val1 > val2 ? val1 : val2;

  let r1 = takeC(num1, 10**p);
  let r2 = takeC(num2, 10**p);

  let total = divideC((r1 - r2) , (10**p));
  return total
}

/**
*@Author: QWP
*@Description: 数据乘法
*@Date 2024-07-18 12:41
*/
export const takeC = (num1: number, num2: number) => {
  let baseNum = 0;
  try{
    baseNum += num1.toString().split(".")[1].length;
  }catch(e){}
  try{
    baseNum += num2.toString().split(".")[1].length;
  }catch(e){}
  return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum); 
}


/**
*@Author: QWP
*@Description: 除法
*@Date 2024-07-18 12:41
*/
export const divideC = (num1: number, num2: number) => {
  let baseNum1 = 0, baseNum2 = 0; 
  let baseNum3, baseNum4; 
  let powFinal;
  try { 
    baseNum1 = num1.toString().split(".")[1].length; 
  } catch (e) { 
    baseNum1 = 0; 
  } 
  try { 
    baseNum2 = num2.toString().split(".")[1].length; 
  } catch (e) { 
    baseNum2 = 0; 
  } 
  
  baseNum3 = Number(num1.toString().replace(".", "")); 
  baseNum4 = Number(num2.toString().replace(".", "")); 
  if(Math.pow(10, baseNum2 - baseNum1) >= 1) {
    powFinal = Math.pow(10, baseNum2 - baseNum1)
  } else {
    powFinal = Math.pow(10, baseNum2 - baseNum1).toFixed(Math.abs(baseNum2 - baseNum1))
  }
  return takeC((baseNum3 / baseNum4), powFinal); 
}

export default {
  addC,
  reduceC,
  takeC,
  divideC
}